package edu.ynu.se.xiecheng.achitectureclass.service;

import edu.ynu.se.xiecheng.achitectureclass.dao.GreenhouseDao;
import edu.ynu.se.xiecheng.achitectureclass.dto.DeviceDataWithGreenhouseDTO;
import edu.ynu.se.xiecheng.achitectureclass.entity.DeviceDataBase;
import edu.ynu.se.xiecheng.achitectureclass.entity.Greenhouse;
import org.springframework.beans.factory.annotation.Autowired;

import javax.persistence.EntityManager;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class DeviceData_3ServiceImpl extends DeviceDataServiceImpl{
    @Autowired
    private EntityManager entityManager;

    @Autowired
    private IDeviceService deviceService;

    @Autowired
    private GreenhouseDao greenhouseDao;

    @Override
    public List<DeviceDataWithGreenhouseDTO> getAllSensorsData(Long greenhouseId) {
        List<DeviceDataBase> sensors = new ArrayList<>();
        Greenhouse greenhouse = greenhouseDao.findById(greenhouseId).orElse(null);

        if (greenhouse == null) {
            throw new RuntimeException("Greenhouse not found");
        }

        // 查询土壤氮含量传感器
        String jpql = "SELECT s FROM DeviceData_3 s WHERE s.isDeleted = 0 AND s.greenhouseId = :greenhouseId ORDER BY s.timestamp DESC";
        sensors.addAll(entityManager.createQuery(jpql)
                .setParameter("greenhouseId", greenhouseId)
                .setMaxResults(1)
                .getResultList());

        return super.getAllSensorsData(greenhouseId);
    }
}
